package com.gwd.task.services.impl;

import com.gwd.task.entity.UserGroupEntity;
import com.gwd.task.model.GroupDTO;
import com.gwd.task.repository.UserGroupRepository;
import com.gwd.task.services.UserGroupServer;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhiyongming
 * @date 2020/11/10 19:38
 */
@Service
public class UserGroupServerImpl implements UserGroupServer {

    @Resource
    private UserGroupRepository userGroupRepository;

    @Override
    public List<Long> findByGroup(Long group) {
        UserGroupEntity entity = new UserGroupEntity();
        entity.setGroupId(group);
        return userGroupRepository.findAll(Example.of(entity)).stream()
                .map(UserGroupEntity::getUserId).collect(Collectors.toList());
    }

    /**
     * 更新关联明细
     * 1。删除已有
     * 2. 重新新增一遍
     * @param groupId 组别id
     * @param userIdList 人员id list
     */
    @Override
    public void save(Long groupId, List<Long> userIdList) {
        userGroupRepository.deleteByGroupId(groupId);
        if (userIdList.size()!=0) {
            List<UserGroupEntity> list = new ArrayList<>();
            userIdList.forEach(i -> list.add(new UserGroupEntity(groupId, i)));
            userGroupRepository.saveAll(list);
        }
    }

    @Override
    public List<Long> findGroupIdListByUserId(Long userId) {
        List<UserGroupEntity> userGroupEntityList = userGroupRepository.findByUserId(userId);
        if (userGroupEntityList==null) {
            return new ArrayList<>();
        }
        return userGroupEntityList.stream().map(UserGroupEntity::getGroupId).collect(Collectors.toList());
    }
}
